import Schema from 'validate'
const mobileSchema = new Schema({
  mobile:{
    type:String,
    required:true,
    match:/^1[3-9]\d{9}$/,
    message:'手机号不正确'
  },
  
})
const codeSchema = new Schema({
  code:{
    type:String,
    required:true,
    match:/^\d{6}$/,
    message:'验证码不正确'
  }
})
Page({
  data: {
    countDownVisible: false,
    nnn:"ppp",
    mobile:'15915698546',
    code:''
  },

  async getCode(){
    const data = {mobile : this.data.mobile}
    const err = mobileSchema.validate(data)
    console.log(err);
    if(err.length){
      wx.utils.toast(err[0].message)
      return
    }
    const res =  await wx.http({
       url:'/code',
       data
     })
     this.setData({countDownVisible:true})
     console.log(res);
  },
  async login(){
    const { mobile , code } = this.data
    const errMobile = mobileSchema.validate({mobile})
    if(errMobile.length){
      wx.utils.toast(err[0].message)
      return
    }
    const errcode = codeSchema.validate({code})
    if(errcode.length){
      wx.utils.toast(err[0].message)
      return
    }
    const res = await wx.http({
      url:'/login',
      data:{
        mobile,
        code
      },
      method:'POST'
    })
    console.log(res);
    const app = getApp()
    const {token,refreshToken} = res.data
    app.setToken(token,refreshToken)
    if(this.redirect){
      wx.reLaunch({
        url: '/' + this.redirect
      })
    } else {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  },
  onLoad({redirect}){
    console.log(redirect);
     this.redirect = redirect
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
})
